#include <QDir>
#include <QFileDialog>
#include <QMdiSubWindow>
#include <QDomDocument>
#include <QMessageBox>
#include "headers/openexaroreport.h"
#include "exaro/include/reportengine.h"

OpenExaroReport::OpenExaroReport(QWidget *parent) :
    QWidget(parent)
{
    setupUi(this);
    reportFile->setVisibleClearButtron(false);
}

void OpenExaroReport::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        retranslateUi(this);
        break;
    default:
        break;
    }
}

void OpenExaroReport::on_reportFile_runButtonClicked()
{
    QString reportDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName( this, tr( "Open report" ),
                                                     reportDir , tr( "Report (*.bdrt)" ) );
    if ( !fileName.size() )
        return;
    reportFile->setText(fileName);
    buttonLoad->setEnabled(true);
}

void OpenExaroReport::on_buttonClose_clicked()
{
    QWidget *parent = this->parentWidget();
    while (parent) {
        QMdiSubWindow *subWindow = qobject_cast<QMdiSubWindow *>(parent);
        if (subWindow) {
            subWindow->close();
            break;
        }
        parent = parent->parentWidget();
    }
}

void OpenExaroReport::on_buttonLoad_clicked()
{
    Report::ReportInterface* m_report=0;
    Report::ReportEngine m_reportEngine;
    QSqlDatabase db = QSqlDatabase::database();
    m_report = m_reportEngine.loadReport(reportFile->text());
    if (!m_report)
    {
        QMessageBox::warning(this, tr("Ошибка"),tr("Не удалось загрузить файл отчёта!!!"),tr("Закрыть"));
        return;
    }
    m_report->setDatabase(db);
    if (!m_report->exec())
    {
        QMessageBox::warning(this, tr("Ошибка"),tr("Не удалось выволнить отчёт!!!"),tr("Закрыть"));
        delete m_report;
        return;
    }
    delete m_report;
}
